package com.aplink.generic.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.os.Environment;

import com.aplink.generic.controller.GenericApplication;

public class DatabaseBackup {
    public void writeToSD(final Context context) throws IOException {
        final File sd = Environment.getExternalStorageDirectory();
        if (sd.canWrite()) {
            final String DATABASE_NAME = GenericApplication.getInstance()
                    .getDatabaseName();
            final String backupDBPath = String.format("bak_%s",
                    GenericApplication.getInstance().getDatabaseName());
            final File currentDB = context.getDatabasePath(DATABASE_NAME);
            final File backupDB = new File(sd, backupDBPath);
            backupDB.createNewFile();
            if (currentDB.exists()) {
                final FileInputStream fileInputStream = new FileInputStream(
                        currentDB);
                final FileOutputStream fileOutputStream = new FileOutputStream(
                        backupDB);
                final byte[] buffer = new byte[1024];
                while (fileInputStream.read(buffer) != -1) {
                    fileOutputStream.write(buffer);
                }
                fileInputStream.close();
                fileOutputStream.close();
            }
        }
    }
}
